/**
 * form - jQuery xui
 *
 * Licensed under the GPL:
 *   http://www.gnu.org/licenses/gpl.txt
 *
 * Copyright 2013 xjb [ beymy.en@gmail.com ]
 *
 * 依赖
 *   mask
 */
(function($) {
    /**
     * ajax提交表单
     */
    function ajaxSubmit(target, options) {
        options = options || {};

        if (options.onSubmit) {
            if (options.onSubmit.call(target) == false) {
                return;
            }
        }

        var form = $(target);
        if (!options.url) {
            options.url = form.attr('action');
        }

        form.mask().mask('show');
        $.ajax({
            type: 'POST',
            url: options.url,
            dataType: 'json',
            data: form.serialize(),
            success: function(data) {
                form.mask('hide');
                options.success.call(target, data);
            },
            error: function() {
                form.mask('hide');
            }
        });
    }

    /**
     * 加载表单数据
     * 如果data是string类型则代表URL,从远程加载数据
     * 否则加载本地object
     */
    function load(target, data) {
        if (typeof data == 'string') {
            $.ajax({
                url: data,
                dataType: 'json',
                success: function(data) {
                    _load(data);
                }
            });
        } else {
            _load(data);
        }

        function _load(data) {
            var form = $(target);
            for (var name in data) {
                var val = data[name];
                $('input[name="' + name + '"]', form).val(val);
                $('textarea[name="' + name + '"]', form).val(val);
                $('select[name="' + name + '"]', form).val(val);
                if ($.fn.combobox) {
                    $('select[comboboxName="' + name + '"]', form).combobox('setValue', val);
                }
            }
        }
    }

    /**
     * 清空表单
     */
    function clear(target) {
        $('input,select,textarea', target).each(function() {
            var t = this.type,
                tag = this.tagName.toLowerCase();
            if (t == 'text' || t == 'password' || tag == 'textarea')
                this.value = '';
            else if (t == 'checkbox' || t == 'radio')
                this.checked = false;
            else if (tag == 'select')
                this.selectedIndex = -1;

        });
    }

    /**
     * 重置表单
     */
    function reset(target) {
        target.reset();
    }

    /**
     * 验证表单
     */
    function validate(target) {
        if ($.fn.validatebox) {
            var t = $(target);
            t.find('.validatebox-text:not(:disabled)').validatebox('validate');
            var invalidbox = t.find('.validatebox-invalid');
            invalidbox.filter(':not(:disabled):first').focus();
            return invalidbox.length == 0;
        }
        return true;
    }

    $.fn.form = function(options, param) {
        if (typeof options == 'string') {
            return $.fn.form.methods[options](this, param);
        }
    };

    $.fn.form.methods = {
        submit: function(jq, options) {
            return jq.each(function() {
                ajaxSubmit(this, $.extend({}, $.fn.form.defaults, options || {}));
            });
        },
        load: function(jq, data) {
            return jq.each(function() {
                load(this, data);
            });
        },
        clear: function(jq) {
            return jq.each(function() {
                clear(this);
            });
        },
        reset: function(jq) {
            return jq.each(function() {
                reset(this);
            });
        },
        validate: function(jq) {
            return validate(jq[0]);
        }
    };

    $.fn.form.defaults = {
        url: null,
        onSubmit: function() {},
        success: function(data) {}
    };
})(jQuery);
